package com.heba.helper;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;

import com.heba.AppManager;
import com.heba.Debug;
import com.heba.dialog.ErrorDialog;
import com.heba.greenmulu.GuideActivity;
import com.heba.greenmulu.R;
import com.loopj.android.http.TextHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 * JSONHttpHelper
 * <p>
 * Created by shenghao on 2015/5/14.
 */
public class JSONHttpHelper extends Activity {

    public static class JSONHttpResponseHandler extends TextHttpResponseHandler {
        public Context context;
        public String error = "";
        public String errorMessage = "";
        public String response;
        public JSONArray datas;
        //        public JSONObject pages;
        public int total;
        //        public int perpage;
//        public int totalpage;
//        public int page;
//        public int totalNum;
        public boolean rawResponse = false;

        public JSONHttpResponseHandler(Context context) {
            this.context = context;
        }

        public void Success() {

        }

        public void Failure() {
            try {
                if (context == null)
                    return;
                if (error == null || error.isEmpty())
                    return;

                //同一个账号在另一设备登录时的处理
                if (error.toUpperCase().equals("ERR_USER_NOT_LOGGED_IN")) {
                    ErrorDialog.showWithConfirmClick(context, context.getResources().getString(R.string.tips),
                            ResourceHelper.getResourceString("ERR_USER_NOT_LOGGED_IN", context), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    MemberShipHelper.logOut();
                                    context.startActivity(new Intent(context, GuideActivity.class));
                                    AppManager.getAppManager().finishAllActivity();
                                }
                            });
                    return;
                }

                //服务器超时
                if (error.toUpperCase().startsWith("CONNECTION TO") ||
                        error.toUpperCase().startsWith("NOT FOUND") || error.toUpperCase().startsWith("CONNECT TO") ||
                        error.toUpperCase().startsWith("BAD GATEWAY")) {
                    ErrorDialog.Show(context, context.getResources().getString(R.string.tips),
                            ResourceHelper.getResourceString("server_timeout_error", context));
                    return;
                }

                //内部服务器错误
                if (error.toUpperCase().startsWith("INTERNAL SERVER ERROR")) {
                    ErrorDialog.Show(context, context.getResources().getString(R.string.tips), ResourceHelper.getResourceString("internal_server_error", context));
                    return;
                }

                if (!error.toUpperCase().startsWith("ERR_SESSIONKEY")){
                    //显示服务器返回的错误信息
                    ErrorDialog.Show(context, context.getResources().getString(R.string.tips),
                            ResourceHelper.getResourceString(error.toUpperCase(), context));
                }

            } catch (Exception e) {
                e.printStackTrace();
                Debug.Log("Failure Exception", error);
            }
        }

        public String ErrorMessage() {
            if (error == null) error = "";
            if (errorMessage == null || errorMessage.equals("null")) errorMessage = "";
            if (errorMessage.equals("")) return error;
            return errorMessage;
        }

        @Override
        public void onFailure(int i, Header[] headers, String responseBody, Throwable throwable) {
            // Response failed
            error = throwable.getMessage();
            errorMessage = error;
            Debug.Log("JSONHttpResponseHandler onFailure " + error, responseBody);
            Failure();
        }

        @Override
        public void onSuccess(int i, Header[] headers, String responseBody) {
            response = responseBody;

            //服务器返回信息
            Debug.Log("server response:", response);

            if (rawResponse) {
                Success();
                return;
            }
            try {
                JSONObject json = new JSONObject(response.trim());

//                if (json.has("Data")) {
//                    datas = (JSONArray) json.get("Data");
//                } else if (json.has("data")) {
//                    datas = (JSONArray) json.get("data");
//                }

                if (json.has("Pages")) {
                    JSONObject object = json.getJSONObject("Pages");
                    total = object.getInt("Total");
                }

                if (json.has("Error")) {
                    error = json.getString("Error");
                }

                if (!error.trim().equals("")) {
                    Debug.Log(error, response);
                    Failure();
                    return;
                }

                Success();
                Debug.Log("JSON success", "triggered");

            } catch (Exception e) {
                e.printStackTrace();
                //the server return unexpected error
                Debug.Log("JSON Decode Error", response);
                error = "ERR_ServerError";
                Failure();
                return;
            }

        }
    }
}
